<?php

namespace app\zhan\home;

use app\zhan\util\Wechat;

/**
 *
 */
class Auth extends Common
{
    const REFRESH_INTERVAL = 3600 * 24 * 7;
    public function _initialize()
    {
        parent::_initialize();
        $this->uid = 10;
        // if (!session('auth')) {
        //     $auth = $this->login();
        //     session('auth', $auth);
        // }

        // $auth              = isset($auth) ? $auth : session('auth');
        // $this->uid         = $auth['id'];
        // $this->member_info = $auth;
    }

    public function login()
    {
        $oauth        = Wechat::getSdk('Oauth');
        $redirect_uri = $this->request->baseUrl(true);

        $acc_arr = $oauth->getOauthAccessToken();
        if (false === $acc_arr) {
            $oauth_url = $oauth->getOauthRedirect($redirect_uri, 0, 'snsapi_base');
            $this->redirect($oauth_url);
        }

        $openid             = $acc_arr['openid'];
        $oauth_access_token = $acc_arr['access_token'];

        $member  = model('zhan_member');
        $_member = $member->where(['openid' => $openid])->find();
        if ($_member) {
            if (time() - $_member['update_time'] < self::REFRESH_INTERVAL) {
                return $_member->toArray();
            } else {
                $userinfo = $oauth->getOauthUserinfo($oauth_access_token, $openid);
                if (isset($userinfo['nickname'])) {
                    $_member->save($userinfo);
                    return $_member->toArray();
                }
            }
        };

        $userinfo = isset($userinfo) ? $userinfo : $oauth->getOauthUserinfo($oauth_access_token, $openid);
        if (isset($userinfo['nickname'])) {
        	$userinfo['ip'] = $this->request->ip();
            $member->save($userinfo);
            return $member->toArray();
        }

        $oauth_url = $oauth->getOauthRedirect($redirect_uri, 1, 'snsapi_userinfo');
        $this->redirect($oauth_url);
    }

}
